package com.cgnpc.scp.common.controller;

import cn.com.cgnpc.aep.bizcenter.filecenter.api.vo.FileUrlVO;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.bean.ScpApiResult;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.service.DownloadFileService;
import com.cgnpc.scp.common.service.FileCenterService;
import com.cgnpc.scp.common.utils.AjaxResultUtil;
import com.cgnpc.scp.common.utils.ExceptionUtil;
import com.cgnpc.scp.common.utils.JacksonUtil;
import com.cgnpc.scp.common.utils.ListUtil;
import com.cgnpc.scp.common.utils.MediaTypeUtil;
import com.cgnpc.scp.common.utils.RequestUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/******************************
 * 用途说明: SCP公共下载文件
 * 作者姓名: yblrs
 * 创建时间: 2020/8/20 22:20
 ******************************/
@Controller
@RequestMapping("/scp/common/downloadFile")
public class ScpCommonFileDownloadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScpCommonFileDownloadController.class);

    @Autowired
    private CurrentUser currentUser;

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private FileCenterService fileCenterService;

    @Autowired
    private DownloadFileService downloadFileService;

    /**********************************
     * 用途说明: SCP公共下载文件---从文件服务器下载附件
     * 参数说明: HttpServletRequest request, HttpServletResponse response
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "SCP公共下载文件---从文件服务器下载附件")
    @RequestMapping(value = "/downloadFileFromFileCenter", method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadFileFromFileCenter(HttpServletRequest request, HttpServletResponse response) {
        final String logInfo = "[downloadFileFromFileCenter_UUID_" + UUID.randomUUID().toString() + "]";
        AjaxResult ajaxResult = null;
        boolean reqHeaderPrintDebugInfo = false;
        final List<Object> downloadFileResult = new ArrayList<>();
        final List<Object> downloadFileDebugInfoList = new ArrayList<>();
        boolean usedEndResponse = true;

        try {
            reqHeaderPrintDebugInfo = "Y".equals(request.getHeader(RequestUtil.HEADER_CUSTOM_PRINT_DEBUG_INFO));

            if (reqHeaderPrintDebugInfo) {
                String reqHeaderInfo = RequestUtil.getHeaderInfo(request);
                LOGGER.info("{}reqHeaderInfo:{};", logInfo, reqHeaderInfo);
                downloadFileDebugInfoList.add(reqHeaderInfo);
            }

            // 获取当前的登录用户信息
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            // 获取请求的语言reqLocale，cookie需要包含lang=cn，或者lang=en
            Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

            String reqFileCenterFileId =  "";

            reqFileCenterFileId = reqFileCenterFileId + request.getParameter("fileCenterFileId");

            LOGGER.info("{}reqFileCenterFileId:{};"
                    , logInfo
                    , reqFileCenterFileId
            );

            if (reqHeaderPrintDebugInfo) {
                downloadFileDebugInfoList.add("reqFileCenterFileId:[" + reqFileCenterFileId + "];");
            }

            if (StringUtil.isNullOrSpace(reqFileCenterFileId)) {
                ajaxResult = AjaxResultUtil.createI18nErrorDefaultMessage(
                        reqLocale
                        , messageSource
                );
                return;
            }

            List<String> usedFileCenterFileIdList = null;
            usedFileCenterFileIdList = Arrays.asList(reqFileCenterFileId);

            // 获取全新的文件url
            ScpApiResult<List<FileUrlVO>> apiResultWithFileUrlVO = fileCenterService.getUrlFromFileCenterManager(
                    loginUserInfo
                    , usedFileCenterFileIdList
                    , reqHeaderPrintDebugInfo
                    , downloadFileDebugInfoList
            );

            if (reqHeaderPrintDebugInfo) {
                downloadFileDebugInfoList.add(apiResultWithFileUrlVO);
                downloadFileDebugInfoList.add("apiResultWithFileUrlVO:" + JacksonUtil.writeValueAsString(apiResultWithFileUrlVO));
            }

            if (apiResultWithFileUrlVO == null || ListUtil.getListSizeWith0(apiResultWithFileUrlVO.getData()) <= 0) {
                ajaxResult = AjaxResultUtil.createI18nErrorDefaultMessage(
                        reqLocale
                        , messageSource
                );
                return;
            }

            List<FileUrlVO> apiResultWithFileUrlVODataList = apiResultWithFileUrlVO.getData();

            if (ListUtil.getListSizeWith0(apiResultWithFileUrlVODataList) > 0) {
                FileUrlVO fileUrlVO = apiResultWithFileUrlVODataList.get(0);

                LOGGER.info("{}needDownloadFile;fileUrlVO:{};"
                        , logInfo
                        , JacksonUtil.writeValueAsString(fileUrlVO)
                );

                usedEndResponse = false;
                String fileUrlVOFileUrl = fileUrlVO.getFileUrl();
                String fileNameWithResponse = fileUrlVO.getFileName();
                downloadFileService.downloadFile(request, response, fileUrlVOFileUrl, fileNameWithResponse);
                return;
            }

            ajaxResult = AjaxResultUtil.createI18nSuccessDefaultMessage(
                    reqLocale
                    , messageSource
            );
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);

            usedEndResponse = true; // 注意，在这里不一定成功

            if (reqHeaderPrintDebugInfo) {
                downloadFileDebugInfoList.add("error:" + ExceptionUtil.getErrorMessage(e));
            }

            ajaxResult = AjaxResultUtil.createI18nErrorDefaultMessage(request, messageSource, downloadFileResult);
        } finally {
            if (ajaxResult != null) {
                ajaxResult.put("___debugInfo", downloadFileDebugInfoList);
            }

            if (usedEndResponse) {
                responseTextPlain(response, ajaxResult);
            }
        }
    }

    private void responseTextPlain(HttpServletResponse response, AjaxResult ajaxResult) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaTypeUtil.TEXT_PLAIN_UTF8_VALUE);
            response.getWriter().println(JacksonUtil.writeValueAsString(ajaxResult));
        } catch (Exception e) {
            LOGGER.error("responseTextPlain;error", e);
        }
    }

}
